package com.jfsnpm.common;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.jfinal.plugin.activerecord.Db;

public class AppTool {
	/**
	 * 获取UUID
	 * @return UUID
	 */
	public static String  getUUID(){
		return  java.util.UUID.randomUUID().toString().replaceAll("-", "");
	}
	/**
	 * json字符串转化为MenuTree对象
	 * @param jsonstring
	 * @return
	 */
	public static MenuTree json2MenuTree(String jsonstring){
		return json2Object(jsonstring, MenuTree.class);
	}
	/**
	 * json字符串转化为MenuTree4Auth对象
	 * @param jsonstring
	 * @return
	 */
	public static MenuTree4Auth json2MenuTree4Auth(String jsonstring){
		return json2Object(jsonstring, MenuTree4Auth.class);
	}
	
	public static OrgTree json2OrgTree(String jsonstring){
		return json2Object(jsonstring, OrgTree.class);
	}
	/**
	 * 通用json字符串转Object
	 * @param jsonstring
	 * @param clazz
	 * @return
	 */
	public static <T> T json2Object(String jsonstring,Class<T> clazz){
		if (StringUtils.isBlank(jsonstring)) {
            return null;
        }
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		try {
			return mapper.readValue(jsonstring, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * Object转换为json字符创
	 * @param object
	 * @return
	 */
	public static String object2Json(Object object){
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 判断表是否存在
	 * @param tableName
	 * @return
	 */
	public static boolean tableIsExists(String tableName){
		if(StringUtils.isBlank(tableName)) return false;
		if(Db.queryNumber(AppSql.getsql("pm.isexists"),tableName).longValue() > 0 ) return true;
		return false;
	}
}
